package com.tenclass.common.interceptor;

import cn.ilanxin.common.error.ContextExceptionV2;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import java.io.IOException;

import static feign.FeignException.errorStatus;

/**
 * 下游业务错误自动解码
 * @author YIJIUE
 * @since 1.1.5
 */
public class FeignErrorDecoder implements ErrorDecoder {

    private static final Logger logger = LoggerFactory.getLogger(FeignErrorDecoder.class);

    private final ObjectMapper objectMapper;

    public FeignErrorDecoder(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            String message = null;
            try {
                message = Util.toString(response.body().asReader());
                return objectMapper.readValue(message, ContextExceptionV2.class);
            } catch (IOException e) {
                logger.error("read stream exception : {}, | bug : {}", methodKey, e);
                throw new RuntimeException(e.getMessage());
            } catch (Exception e) {
                throw new RuntimeException(message);
            }
        }
        return errorStatus(methodKey, response);
    }
}
